<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="24" :xs="24">
        <el-form
          :model="queryParams"
          ref="queryRef"
          :inline="true"
          v-show="showSearch"
          label-width="68px"
        >
          <div style="display: flex; flex-wrap: wrap; width: 100%">
            <el-col :span="6">
              <el-form-item label="用户账号" prop="userName">
                <el-input
                  v-model="queryParams.userName"
                  placeholder="请输入用户名称"
                  clearable
                  style="width: 240px"
                  @keyup.enter="handleQuery"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="手机号码" prop="phonenumber">
                <el-input
                  v-model="queryParams.phonenumber"
                  placeholder="请输入手机号码"
                  clearable
                  style="width: 240px"
                  @keyup.enter="handleQuery"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="状态" prop="status">
                <el-select
                  v-model="queryParams.status"
                  placeholder="用户状态"
                  clearable
                  style="width: 240px"
                >
                  <el-option
                    v-for="dict in sys_normal_disable"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="添加时间" style="width: 308px">
                <el-date-picker
                  style="width: 100%"
                  v-model="timeData"
                  start-placeholder="开始"
                  end-placeholder="结束"
                  range-separator="-"
                  type="datetimerange"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  unlink-panels
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery"
                  >搜索</el-button
                >
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-col>
          </div>
        </el-form>

        <el-table
          v-loading="loading"
          :data="userList"
          @selection-change="handleSelectionChange"
        >
          <el-table-column label="账号ID" align="center" prop="userId" />
          <el-table-column label="账号名称" align="center" prop="userName" />
          <el-table-column label="手机号" align="center" prop="phonenumber" />
          <el-table-column
            label="添加时间"
            align="center"
            prop="createTime"
            width="160"
          >
            <template #default="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="180"
            class-name="small-padding fixed-width"
          >
            <template #default="{ row }">
              <div>
                <el-button
                  type="text"
                  @click="handleAllocation(row)"
                  v-hasPermi="['setting:permissions:allocwarehouse']"
                  >分配仓库</el-button
                >
                <el-button
                  type="text"
                  @click="handleRecord(row)"
                  v-hasPermi="['setting:permissions:loglist']"
                  >操作记录</el-button
                >
              </div>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 分配仓库 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form :model="form" ref="userRef" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="仓库11">
              <el-checkbox-group v-model="form.warehouseIds">
                <el-checkbox v-for="item in warehouseList" :label="item.value">
                  <template #default> {{ item.label }} </template>
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <OperationRecords
      v-if="isShowDialog"
      :isShowDialog="isShowDialog"
      :current-user-id="currentUserId"
      @cancel="handleClose"
    />
  </div>
</template>

<script setup name="User">
import { listUser, allocWarehouse, getWarehouseList } from "@/api/system/user";
import { nextTick, ref } from "vue";
import OperationRecords from "@/views/settings/components/operationRecords.vue";

const { proxy } = getCurrentInstance();
const { sys_normal_disable } = proxy.useDict("sys_normal_disable");

const userList = ref([]);
const isShowDialog = ref(false);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const timeData = ref([]);

const currentUserId = ref(null);

const data = reactive({
  form: {
    warehouseIds: [],
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userName: undefined,
    phonenumber: undefined,
    status: undefined,
    warehouseId: undefined,
  },
});

const { queryParams, form } = toRefs(data);

let tableHeight = ref(0);
nextTick(() => {
  tableHeight.value = window.innerHeight - 400;
});
window.onresize = () => {
  tableHeight.value = document.body.scrollHeight - 400;
};

/** 查询用户列表 */
function getList() {
  loading.value = true;
  queryParams.value.startTime = timeData.value[0];
  queryParams.value.endTime = timeData.value[1];
  let params = {
    pageNum: queryParams.value.pageNum,
    pageSize: queryParams.value.pageSize,
    param: queryParams.value,
  };
  listUser(params).then((res) => {
    loading.value = false;
    userList.value = res.data;
    total.value = res.total;
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  timeData.value = [];
  proxy.resetForm("queryRef");
  queryParams.value.warehouseId = undefined;
  proxy.$refs.deptTreeRef.setCurrentKey(null);
  handleQuery();
}

/** 选择条数  */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.userId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 修改按钮操作 */
function handleAllocation(row) {
  open.value = true;
  loadSelectData(row);
}

const warehouseList = ref([]);
function loadSelectData(row) {
  const userId = row.userId;
  getWarehouseList({ userId }).then((res) => {
    form.value.userId = userId;
    res.data.forEach((item) => {
      if (item.checked) {
        form.value.warehouseIds.push(item.warehouseId);
      }
    });
    warehouseList.value = res.data.map((item) => {
      return {
        label: item.warehouseName,
        value: item.warehouseId,
      };
    });
  });
}

/** 提交按钮 */
function submitForm() {
  allocWarehouse(form.value).then(() => {
    proxy.$modal.msgSuccess("修改成功");
    open.value = false;
    getList();
    reset();
  });
}

getList();

function reset() {
  form.value = {
    userId: undefined,
    warehouseIds: [],
  };
}

function handleRecord({ userId }) {
  currentUserId.value = userId;
  isShowDialog.value = true;
}
function handleClose() {
  isShowDialog.value = false;
}
</script>
